Search code examples
phpmysqlmysqliserver-side

Subqueries for results


Hello I`m trying to get few columns from two tables.

I need to read the information from table 1

SELECT `id`, `title`, `body`, `userid`, `cdate`, `tags` FROM `asks` WHERE `id`= ? AND `title`= ?

and I need to get information about the user who published this. his id as the userid in the previous query. and to get information about the user I need more query:

SELECT `username`, `fullname`, `asked`, `answered` FROM `accounts` WHERE `id`=

I must to echo all these information to one page. Thank so much.


Solution

  • You can join the two tables together like this:

    SELECT `id`, `title`, `body`, `userid`, `cdate`, `tags`, `username`, `fullname`, `asked`, `answered` FROM `asks` inner join `accounts` on accounts.id=tags.id WHERE `id`= ? AND `title`= ?
    

    And that will only select when a record is present in both tables otherwise you can use a different type of join Visual Explanation Of SQL Joins