SQL join on返回无值

时间:2014-10-03 13:35:19

标签: sql mariadb

//编辑发现问题。我将所有类型从text更改为varchar。现在它工作正常。

我有一张名为" sound"看起来像这样:

  

rowID 类型int(11)| userID 输入文字| 名称键入文字| 声音文件输入文字
  1 | " mod001:02" | "麦" | "音乐/ Song.mp3的"

和一个名为" soundlist"看起来像这样:

  

soundID 输入int(11)| 名称键入文字| soundfile 输入文字| 使用类型tinyint(1)
  1 | " topSong" | "音乐/ Song.mp3的" | 1

我的问题是,当我运行此查询时

SELECT *
FROM sounds
INNER JOIN soundlist
ON STRCMP(soundlist.soundfile, sounds.soundfile) = 0
WHERE STRCMP(sounds.userID, "mod001:02") = 0;

我得到一个空的结果!

我的目标是设置" soundlist.used"到0.我只有" sounds.userID"给出。 我目前正在使用此查询:

UPDATE soundlist
INNER JOIN sounds
ON STRCMP(sounds.userID, "mod001:02") = 0
SET soundlist.used = 0
WHERE STRCMP(soundlist.soundfile, sounds.soundfile) = 0;

3 个答案:

答案 0 :(得分:0)

编辑:这会将sounds.userid更新为" 0"其中soundlist.used是" 1"

UPDATE sounds 
INNER JOIN soundlist ON
    sounds.soundfile = soundlist.soundfile
SET sounds.userid = "0" 
WHERE soundlist.used = "1"

如果您希望sounds.userid等于soundlist.us

UPDATE sounds 
INNER JOIN soundlist ON
    sounds.soundfile = soundlist.soundfile
SET sounds.userid = soundlist.used 

答案 1 :(得分:0)

您可以使用嵌套查询:

UPDATE soundlist
    set soundlist.used=0
    where soundfile IN (               -- using IN keyword instead of = if you want to update multiple entries
        select sounds.soundfile
            from sounds
            where sounds.rowID=1       -- or any other condition
    );

我假设rowID是INT。

如果你想更进一步,不打扰比较字符串,为什么不使用外键?

让我们听起来一样:

rowID | userID      | name    | soundfile
    1 | "mod001:02" | "Jimmy" | "music/song.mp3"

修改声音列表以引用声音:

soundID | name      | soundId   | used
      1 | "topSong" | 1         | 1

您的查询:

SELECT *
FROM sounds
INNER JOIN soundlist
ON STRCMP(soundlist.soundfile, sounds.soundfile) = 0
WHERE STRCMP(sounds.userID, "mod001:02") = 0;

会变成

SELECT *
FROM sounds s
INNER JOIN soundlist l
ON s.rowId=l.soundId
where STRCMP(s.userID, "mod001:02") = 0;

这可以为您节省一个STRCMP。

考虑在用于条件的varchar列上使用索引,它更快,有时更容易读取查询(s.userID =“mod001:02”更加直截了当)

答案 2 :(得分:0)

问题在于你是text数据类型,如果我使用varchar,第一个查询会让我the desired result set

相关问题