MySQL的(@i:=@i+1)用處及用法
如:SELECT (@i:=@i+1),t.* FROM table_name t,(SELECT @i:=0) AS j
(@i:=@i+1)代表定義一個(gè)變量赡突,每次疊加1麸俘;
(SELECT @i:=0) AS j 代表建立一個(gè)臨時(shí)表惧笛,j是隨便取的表名,但別名一定要的拜效。
select student.sname,sum(sc.score),@i :=@i+1 as rank from (select @i := 0) as j,
student,sc
where student.sid = sc.sid
group by student.sname order by sum(sc.score) desc
+-------+---------------+------+
| sname | sum(sc.score) | rank |
+-------+---------------+------+
| 趙雷 | 269.0 | 1 |
| 孫風(fēng) | 240.0 | 3 |
| 錢電 | 210.0 | 2 |
| 周梅 | 163.0 | 5 |
| 李云 | 100.0 | 4 |
| 鄭竹 | 89.0 | 7 |
| 吳蘭 | 65.0 | 6 |
+-------+---------------+------+
7 rows in set (0.01 sec)
MySQL中union和order by同時(shí)使用的實(shí)現(xiàn)方法紧憾。
1昌渤、如果直接用如下sql語句是會(huì)報(bào)錯(cuò):Incorrect usage of UNION and ORDER BY膀息。
SELECT * FROM t1 WHERE username LIKE 'l%' ORDER BY score ASC
UNION
SELECT * FROM t1 WHERE username LIKE '%m%' ORDER BY score ASC
因?yàn)閡nion在沒有括號(hào)的情況下只能使用一個(gè)order by,所以報(bào)錯(cuò)甸赃,這個(gè)語句有2種修改方法埠对。如下:
(1)可以將前面一個(gè)order by去掉裁替,改成如下:
SELECT * FROM t1 WHERE username LIKE 'l%'
UNION
SELECT * FROM t1 WHERE username LIKE '%m%' ORDER BY score ASC
該sql的意思就是先union,然后對(duì)整個(gè)結(jié)果集進(jìn)行order by襟沮。如此一來第一條select語句就無法order by 排序
(2)可以通過兩個(gè)查詢分別加括號(hào)的方式,改成如下:
(SELECT * FROM t1 WHERE username LIKE 'l%' ORDER BY sroce ASC)
UNION
(SELECT * FROM t1 WHERE username LIKE '%m%' ORDER BY score ASC)
這種方式的目的是為了讓兩個(gè)結(jié)果集先分別order by净刮,然后再對(duì)兩個(gè)結(jié)果集進(jìn)行union硅则。如果order by 無效,可改成如下格式:
SELECT * FROM
(SELECT * FROM t1 WHERE username LIKE 'l%' ORDER BY score ASC) t3
UNION
SELECT * FROM
(SELECT * FROM t1 WHERE username LIKE '%m%' ORDER BY score ASC) t4
也就是說怎虫,order by不能直接出現(xiàn)在union的子句中,但是可以出現(xiàn)在子句的子句中蘸际。
2徒扶、union 和 union all 的區(qū)別
union會(huì)過濾掉兩個(gè)結(jié)果集中重復(fù)的行姜骡,而union all不會(huì)過濾掉重復(fù)行。
3惫周、union 和 order by 共存的辦法
SELECT * FROM
(SELECT * FROM t1 WHERE username LIKE 'l%' ) as t3
UNION
SELECT * FROM
(SELECT * FROM t1 WHERE username LIKE '%m%' ) as t4 ORDER BY score ASC
將 ORDER BY 放置在 union 之后
MySQL 不支持使用 LIMIT 子句的 IN/ALL/ANY/SOME 子查詢
意味著下列查詢不能正確的執(zhí)行
select * from my_table where id in (select id from my_table limit 10)
解決方案:再查詢一次 把他變成子句的嵌套,把這個(gè)子句作為t
select * from my_table where id in (select t.id from (select * from my_table limit 10)as t)
##Unknown column in 'where clause'
錯(cuò)誤如題:Unknown column in ‘XXX’ 'where clause'
排查
1递递,查表名是否有錯(cuò)
2啥么,如果sql是在代碼里拼接的,檢查憑借變量的時(shí)候逊躁,是否在變量兩邊加上了單引號(hào)
3隅熙,檢查sql里要查的列囚戚,所對(duì)應(yīng)的條件里的字符串轧简,不是檢查它對(duì)不對(duì),要檢查包含它的引號(hào)是不是中文的,是的話改掉(這個(gè)是我遇到的)
4哮独,如果是子查詢,查一下包含子查詢語句的括弧舟扎,是不是中文的睹限,是的話羡疗,改掉染服。
我錯(cuò)的地方在于
#47.查詢本周過生日的學(xué)生
select student.sname ,weekofyear(CURDATE()) as b,
weekofyear(date_sub(student.sage,INTERVAL year(student.sage) year)) as a
from student where
a = b;
這里就要注意在這種地方引用表名作為變量要加引號(hào) 改成 'a' = 'b'就對(duì)了