簡體   English   中英

在MySQL中聯接兩個表

[英]Joining two tables in MySQL

這是我的兩張桌子。 我不確定它們是否正確歸一化:

all_configurator_lasers_power:

laser_id | power_id | laser_configuration
=========================================
    1       10         1
    1       25         1
    1       20         2
    1       50         2
    2       10         1 ...

all_configurator_power_text:

power_id | power_level | laser_configuration | power_text
========================================================= 
   10        10 watts        1                  10 watt text
   25        25 watts        1                  25 watt text
   20        20 watts        2                  20 watt text
   50        50 watts        2                  50 watt text

如果我要在第一張表中提供laser_id,我要返回的是第二張表的前兩行。

這是我嘗試過的(但是沒有用)

'SELECT * FROM all_configurator_power_text 
 INNER JOIN all_configurator_power_text 
 ON all_configurator_lasers_power.laser_configuration = all_configurator_power_text.laser_configuration'

這將返回如下數組:

Array (
[0] => stdClass Object
        (
            [id] => 1
            [language] => en
            [power_id] => 10
            [power_level] => 10 watts
            [laser_configuration] => 1
            [power_text] => 10 watt text
            [laser_id] => 1
        )
...)

但是該數組(一個CodeIgniter對象)也返回了laser_configuration為2的對象。我只想要那些具有1的對象。我添加了WHERE laser_configuration = 1的WHERE子句,但是隨后出現非對象錯誤。

我究竟做錯了什么?

您需要在WHERE子句中指定要使用哪個表的laser_configuration 這樣做,它應該可以與您編寫的子句一起使用。

因此,您最終會遇到以下情況:

 SELECT * FROM all_configurator_power_text
 INNER JOIN all_configurator_lasers_power 
 ON all_configurator_lasers_power.laser_configuration = all_configurator_power_text.laser_configuration
 WHERE all_configurator_lasers_power.laser_configuration = 1

另外,我建議添加一些速記參考以使其更具可讀性。 這些年來,它可以在保持自己理智的狀態中發揮重要作用:

 SELECT * FROM all_configurator_power_text text
 INNER JOIN all_configurator_lasers_power lasers
 ON lasers.laser_configuration = text.laser_configuration
 WHERE lasers.laser_configuration = 1

嘗試添加以下內容:

WHERE all_configurator_lasers_power.power_id = 1

表結構存在一些潛在的問題,但是如果不了解您的特定要求,就很難說出來。 例如,每個表中都有power_id和laser_configuration。

where子句的可能問題是您需要指定要使用的是兩個表的laser_configuration中的哪個。 即:

WHERE all_configurator_lasers_power.power_id = 1
SELECT *
FROM all_configurator_lasers_power
INNER JOIN all_configurator_power_text
ON all_configurator_lasers_power.laser_id = all_configurator_power_text.laser_configuration
WHERE all_configurator_lasers_power.laser_id = $id (in your case 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM