开发者

Nested or Joins query for MySQL using PHP

I have many a times tried using nested query for MySQL in PHP, but it does not work. Is it not possible to do nested/Joins queries?

Just a Scenario:

I have two tables one table with user id and the other with data. User logins and with sessions I have to cross check two different tables with 开发者_StackOverflow社区user id (user and data). Is it not possible to nest/join these two tables to write a single query statement.

In short is nesting or joining two or more tables permitted in PHP coding?


YES, it is possible to join two or more tables in MySQL (and therefore, also when using PHP).

You need to post your table schema, if you want us to show a relevant join query. You could, however, try something like:

SELECT * FROM user AS t1
CROSS JOIN data AS t2
    ON t1.userid=t2.userid
WHERE t1.userid='154'

(This query presumes that there always will be one row with the userid in both tables. You should use LEFT JOIN instead of CROSS JOIN to return a row even if there is no row in data for the userid. 154 is just an example userid.)

Have a look at http://dev.mysql.com/doc/refman/5.5/en/join.html for information on the JOIN syntax.


users 

| user_id | username | password | enabled |
|---------|----------|----------|---------|
|    1    | john     | sgsd2gg  |   1     |
|    2    | jane     | sdshdhd  |   0     |

users_data

|udata_id| user_id | some_column       | 
|--------|---------|-------------------|
|   1    |   1     | Some title        |
|   2    |   2     | another title     |

Since you haven't posted your table schema, I can't give you an exact solution. But supposing you have a users table and a users_data table, where users_data are owned by a user. You can do a join on the table to retrieve all the data.

SELECT * -- Don't select all fields unless you need it
FROM users U LEFT JOIN users_data UD ON U.user_id = UD.user_id
WHERE U.user_id = 1

This would pull all the records for user with an ID of 1. This is a very simplistic join, but it should give you an idea.

Here's an example that visually describes the different options you can use : SQL Join Differences

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜