简体   繁体   中英

MySQL select statement, query across 2 tables where 1 column matches

I have the following MySQL

    $tutorial = $database->query(
        'SELECT ' . 
            'tutorial.*, ' . 
            'apps.*'.
                'FROM ' . 
                    $database->db_prefix . 'tutorial, ' . 
                    $database->db_prefix . 'apps ' . 
                        'WHERE ' .
                            'apps.title = "' . $name . '" AND apps.id = tutorial.app AND tutorial.relation = "' . $user['id'] . '"'
    );

I want to get the row where apps.title is equal to $name and then get all tutorials based on that retrieved apps id. This acts as a link between the two tables.

Is the above going to work?

in particular:

'apps.title = "' . $name . '" AND apps.id = tutorial.app AND tutorial.relation = "' . $user['id'] . '"'

No, it's not going to work. See the Mysql JOIN syntax.

I want to get the row where apps.title is equal to $name and then get all tutorials based on that retrieved apps id.

From the query you posted above, I think you can JOIN the two tables using the app field something like:

SELECT t.*
FROM tutorials t 
INNER JOIN apps a ON t.app = a.app
WHERE a.title = $name AND t.relation = $user['id']

Or:

SELECT 
  tutorial.*
FROM tutorial
WHERE toutorial.app IN
(
    SELECT app FROM apps WHERE apps.title = $name AND app IS NOT NULL
) AND tutorial.relation = $user['id'] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM