Search code examples
mysqlsqldatabasedebuggingcross-join

How to correctly add 3 columns with 3 particular cells to a table on MySQL?


Note: The following information was created artificially just for educational purposes.

The following query:

SELECT * FROM dapp.credentials WHERE id = ( SELECT MAX(id) FROM dapp.credentials )

gets the following row:

|  id  | email          | password       | first_name | member_type | validated |
---------------------------------------------------------------------------------
|  5000|perkins@drit.com|1234perkins     |Mickey      | regular     |1          |

Now this other query:

SELECT cellphone, address, zipcode FROM dapp.members
WHERE user_id = ( SELECT MAX(user_id) FROM dapp.members )

gets this other row:

| cellphone     | address             | zipcode | 
-------------------------------------------------
| (787)-142-6952|4108 Wheeler Ridge Dr|99563    |

So, how can I create a query that gets a row like this?

|  id  | email          | password       | first_name | member_type | validated || cellphone     | address             | zipcode | 
----------------------------------------------------------------------------------------------------------------------------------
|  5000|perkins@drit.com|1234perkins     |Mickey      | regular     |1          || (787)-142-6952|4108 Wheeler Ridge Dr|99563    |

I tried this query:

SELECT * FROM dapp.credentials WHERE id = ( SELECT MAX(id) FROM dapp.credentials )
JOIN
(SELECT cellphone, address, zipcode FROM dapp.members
WHERE user_id = ( SELECT MAX(user_id) FROM dapp.members ))

But I got this error:

SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'JOIN (SELECT cellphone, address, zipcode FROM dapp.members WHERE user_id = ( S' at line 2

May I know what did I do wrong with my last query?


Solution

  • You can do a CROSS join of the 2 queries:

    SELECT t1.*, t2.*
    FROM (
      SELECT * 
      FROM dapp.credentials 
      WHERE id = (SELECT MAX(id) FROM dapp.credentials)
    ) t1 CROSS JOIN (
      SELECT cellphone, address, zipcode 
      FROM dapp.members 
      WHERE user_id = (SELECT MAX(user_id) FROM dapp.members)
    ) t2;