Home > Net >  how to select two tables which has inner joints and union all tables
how to select two tables which has inner joints and union all tables

Time:09-28

hello I am new to php I am having 2 tables I want to select 2 columns which matches accesstoken and user id column from 2 tables for eg...I had joined (users table and sessions table ) (admin table and adminsessions) now I want to check data either one of these 2 combinations eg....if (users.id=sessions.userid) or (admin.id =adminseesions.userid) I am passing accesstoken in url and I want to match userid and accesstoken is it possible to archive this task with union all because these 2 pairs are independent and I am expecting output as follow if my header has userid which is in adminsessions but not in sessions tabel then I want to display the data which is in adminsessions

I want to display

or if userid from header which matches data in sessions then I want to display following details I want to display

here I want to fetch any single row from above tables based on userid

following are the 2 tables which I want to select one of the table where accesstoken column and userid matches this is the admin session table this is user sessions following are my user and admin table where I want to match one of the id column in two tables this is my user table this is my admin table

CodePudding user response:

Yes, that's possible using UNION.

SELECT * FROM (
    SELECT userid, accesstoken, refreshtoken
      FROM adminsession
    UNION ALL
    SELECT userid, accesstoken, refreshtoken
  FROM sessions) all_sessions
 WHERE userid = :somegivenuserid;

This query will return all session information by :somegivenuserid, regardless of whether this information was found in table adminsession or sessions. In the same way you can get the user data, just that you use tables users and admin. More information can be found in section UNION Clause of MySQL's documentation.

  • Related