简体   繁体   中英

How get data from database with multiply tables?

Hello Guys!

I have a problem with get result from database correctly. I have lot of table but this is not important right now. I have a table look like that:

***PUBLISHER_DEVELOPER table***
pd_id : [int] AUTO PRIMARY
pd_name: [varchar]
pd_type: [integer] (0,1 or 2)

***GAME_INFO table***
g_id: [int] AUTO PRIMARY
g_label: [varchar]
g_publisher: [integer]
g_developer: [integer]

The connections beetwen the tables are this:

PUBLISHER_DEVELOPER : GAME_INFO = 1:LOT

I would like to get the game info with the publisher and developers normal name, but i always got ZERO row returned.

My SQL query:

*SELECT pd_name, pd_name, g_label FROM PUBLISHER_DEVELOPER,GAME_INFO WHERE pd_id = g_publisher AND pd_id = g_developer*

Any idea what i do wrong?

Probably the publisher and developer are different. There should be a relationship between the first table and either the g_publisher or g_developer.

SELECT pd_name, pd_name, g_label FROM PUBLISHER_DEVELOPER INNER JOIN GAME_INFO ON pd_id = g_publisher

SELECT pd_name, pd_name, g_label FROM PUBLISHER_DEVELOPER INNER JOIN GAME_INFO ON pd_id = g_developer

Or

SELECT pd_name, pd_name, g_label FROM PUBLISHER_DEVELOPER LEFT OUTER JOIN GAME_INFO ON pd_id = g_publisher

如果g_publisher和g_developer都引用了PUBLISHER_DEVELOPER.pd_id,那么您可以两次连接到该表。

  SELECT pd_1.pd_name, pd_2.pd_name, gi.g_label FROM PUBLISHER_DEVELOPER pd_1, PUBLISHER_DEVELOPER pd_2, GAME_INFO gi WHERE pd_1.pd_id = gi.g_publisher AND pd_1.pd_id = gi.g_developer;

Assumedly you want two joins to the PUBLISHER_DEVELOPER table to get back both the publisher and the developer.

SELECT p.pd_name AS p_name, d.pd_name AS d_name, g_label
FROM GAME_INFO
JOIN PUBLISHER_DEVELOPER p ON p.pd_id = g_publisher
JOIN PUBLISHER_DEVELOPER d ON d.pd_id = g_developer

SQL Fiddle example

For the query in your comment, a similar rewrite would look something like this.

SELECT f.fk_nev, k.fk_nev, k_nev, j_cim, j_megjelent, j_megjelenes, 
  j_cover, a_becenev, b_head, b_ci?m, b_cimke, b_lead, b_tartalom, 
  b_komment, b_datum, b_burl
FROM jatek_info ji
JOIN fejleszt_kiad f ON f.fk_id = ji.j_fejleszt  
JOIN fejleszt_kiad k ON k.fk_id = ji.j_kiad
JOIN jatek j ON j.j_jatek_info = ji.j_id  
JOIN blog b ON b.b_jatek = j.j_id
JOIN admin a ON a.a_id = b.b_szerzo

I'm guessing to a certain extent how your tables are linked, but I think that should be correct.

Note that there is a ? in one of the field names which I'm assuming is a non-ASCII character that got corrupted when you cut and paste the query into the comment. Be sure to fix that if you're cutting and pasting my code back.

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