我不是很喜欢SQL,我在处理查询时遇到以下问题,这些查询执行某些JOIN并且必须加入相同语言表的2倍。
我正在使用 MySql 。我会尝试解释我的问题。
所以我有这个问题:
SELECT
LSSN.livestock_species_name AS species_name,
LSM.content AS message_content,
LSM.audio_link AS message_audio_link
FROM LivestockDetails AS LSD
INNER JOIN LsMessage AS LSM
ON LSD.ls_message_id = LSM.id
INNER JOIN Languages AS LNG
ON LSM.language_id = LNG.id
INNER JOIN LivestockSpecies AS LSS
ON LSD.live_stock_species_id = LSS.id
INNER JOIN LivestockSpeciesName AS LSSN
ON LSS.id = LSSN.livestock_species_id
INNER JOIN LNG
ON LSSN.language_id = LNG.id
WHERE LSD.live_stock_species_id = 3
AND LSD.ls_area_id = 2
AND LSD.ls_action_type_id = 1
AND LSD.ls_message_id is not null
AND LNG.id = 1
正如您所看到的,我正尝试加入2次 Langunages (由 LNG 取代)。
一旦到了(因为我在特定的语言中有本地化的消息):
INNER JOIN LsMessage AS LSM
ON LSD.ls_message_id = LSM.id
和另一个(因为 LSSN 表包含特定语言的动物名称):
INNER JOIN LNG
ON LSSN.language_id = LNG.id
以这种方式执行它不起作用,我收到此错误消息:
#42000Not unique table/alias: 'LNG'
我认为因为我加入了同一张桌子的两倍。
我可以用这种方式做到并且工作正常:
SELECT
LSSN.livestock_species_name AS species_name,
LSM.content AS message_content,
LSM.audio_link AS message_audio_link
FROM LivestockDetails AS LSD
INNER JOIN LsMessage AS LSM
ON LSD.ls_message_id = LSM.id
INNER JOIN Languages AS LNG
ON LSM.language_id = LNG.id
INNER JOIN LivestockSpecies AS LSS
ON LSD.live_stock_species_id = LSS.id
INNER JOIN LivestockSpeciesName AS LSSN
ON LSS.id = LSSN.livestock_species_id
INNER JOIN Languages AS LNG2
ON LSSN.language_id = LNG2.id
WHERE LSD.live_stock_species_id = 3
AND LSD.ls_area_id = 2
AND LSD.ls_action_type_id = 1
AND LSD.ls_message_id is not null
AND LNG.id = LNG2.id = 1
我加入了一个全新的" INNER JOIN语言AS LNG2 表但我必须以这种方式更改 WHERE 子句:
AND LNG.id = LNG2.id = 1
我在询问它是否是一个好的解决方案,或者是否存在一种更聪明的方法来使用单个表而不是JOIN操作中的 LNG 和 LNG2 表。
答案 0 :(得分:1)
这是您实现目标的另一种方式:
INNER JOIN Languages AS LNG
ON LSM.language_id = LNG.id
INNER JOIN Languages AS LNG2
ON LSM.language_id = LNG2.id AND LSSN.language_id = LNG2.id
我认为你不能将这两个联接合并为一个。
完整查询:
SELECT
LSSN.livestock_species_name AS species_name,
LSM.content AS message_content,
LSM.audio_link AS message_audio_link
FROM LivestockDetails AS LSD
INNER JOIN LsMessage AS LSM
ON LSD.ls_message_id = LSM.id
INNER JOIN Languages AS LNG
ON LSM.language_id = LNG.id
INNER JOIN LivestockSpecies AS LSS
ON LSD.live_stock_species_id = LSS.id
INNER JOIN LivestockSpeciesName AS LSSN
ON LSS.id = LSSN.livestock_species_id
INNER JOIN Languages AS LNG2
ON LSM.language_id = LNG2.id AND LSSN.language_id = LNG2.id
WHERE LSD.live_stock_species_id = 3
AND LSD.ls_area_id = 2
AND LSD.ls_action_type_id = 1
AND LSD.ls_message_id is not null
AND LNG.id = 1