简体   繁体   中英

MySQL Query Involving 3 Tables And 2 Databases, Can't Get Correct Columns

I'm using the following query to pull data from 3 tables. 2 are in the same database and 1 in a different database. Basically I have recipes in one table, and I'm using the recipieToCountry table to connect to the countries table so I know what country a recipe belongs to.

$contentQuery = $page->dbf->query("
  SELECT *
    FROM recipes, recipeToCountry, content.countries
    WHERE recipes.id = recipeToCountry.recipeId 
      AND recipeToCountry.countryId = content.countries.id
      AND content.countries.origId = '$country'
 ");

The problem I'm running into is when I call $content->title it returns the title from countries when I want the title from recipies . My understanding is SELECT * is the issue, so I tried to change the query to this:

SELECT title, description, approved, active, id, recipeId, countryId 
  FROM recipes, recipeToCountry
  WHERE recipes.id = recipeToCountry.recipeId 
UNION 
SELECT id, origId, null, null, null, null, null 
  FROM content.countries
  WHERE content.countries.origId = 1 
    AND recipeToCountry.countryId = content.countries.id

Unfortunately this query has an error, and I'm unsure how to fix it. When I removed the last AND the UNION doesn't seem to work as well. Any ideas on what changes I could make to get the correct columns?

Simple JOINs should work well:

select r.*, c.*
  from recipes r
  join repiceToCountry rc on r.id = rc.recipeId
  join content.countries c on c.id = rc.countryId
  where c.origId = '$country'

You must make sure you have SELECT privileges on the other database.

Also, you can replace r.*, c.* by the specific columns you want to show.

I developed a habit a long time ago of always putting the table alias/name before every field in the query. This way you can modify the query later on without worrying about fields names that conflict when you add tables to the query. I also prefer joins to multiple FROM tables. (It's easier to see the logic)

I would change your first query to this:

SELECT r.*, c.country /* any other fields in country besides title */
FROM recipes as r
LEFT JOIN recipeToCountry as rtc ON rtc.recipeId = r.id
LEFT JOIN content.countries as c ON c.id = rtc.countryId
WHERE c.origId = '$country'

You can leave the word "as" out to make it look a little cleaner, but I leave it in there to show what's happening a little better.

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