 |
ช่วยหน่อยครับ เกี่ยวกับการเขียน sql เพื่อเเสดงข้อมูลของเเต่ละ id ที่ได้มีการกรอกเลข มากกว่า 3 ช่องขึ้นไป |
|
 |
|
|
 |
 |
|
Code (SQL)
select * from tablename where ( if(fld_1 is null, 1,0) + if(fld_2 is null fld_2,1,0) + ....... ) > 3
ปล ..... หมายถีงใส่เพิ่มให้ครบ อย่าเถรตรงนะครับ
|
ประวัติการแก้ไข 2021-01-15 18:12:20 2021-01-15 18:14:02
 |
 |
 |
 |
Date :
2021-01-15 18:10:36 |
By :
Chaidhanan |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
จริงๆ การออกแบบตารางแบบนี้ มันคิวรี่ยากนะครับ
ควรออกแบบดังนี้ดีกว่า
table research_input
id auto_increment
user_id index1
question_id index1 --- รวม 3 รายการสร้างเป็น index
answer_id index1
1, 33, 1, 2
2, 33, 1, 3
3. 33, 2, 1
4, 33. 2, 2
......
แบบนีจะคิวรี่ ง่ายกว่า
|
 |
 |
 |
 |
Date :
2021-01-17 09:17:40 |
By :
Chaidhanan |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Code (SQL)
CREATE TABLE IF NOT EXISTS `tb_research` (
`id` varchar(6) NOT NULL,
`q1` varchar(3) NOT NULL,
`q2` varchar(3) NOT NULL,
`q3` varchar(3) NOT NULL,
`q4` varchar(3) NOT NULL,
`q5` varchar(3) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `tb_research` (`id`, `q1`, `q2`, `q3`, `q4`, `q5`) VALUES
('1', 1, '' , '' , '',2 ),
('2', '' , 1 , '', 3,1),
('3', 3,'' , '' , '',2),
('4', 2 , '' , '', '3', '5');
ตัวอย่างการนับ
Code (SQL)
SELECT
id,
IF(q1>0,1,0) AS check_q1,
IF(q2>0,1,0) AS check_q2,
IF(q3>0,1,0) AS check_q3,
IF(q4>0,1,0) AS check_q4,
IF(q5>0,1,0) AS check_q5,
(IF(q1>0,1,0) + IF(q2>0,1,0) + IF(q3>0,1,0)+ IF(q4>0,1,0)+ IF(q5>0,1,0)) AS count_field
FROM `tb_research`
|
 |
 |
 |
 |
Date :
2021-01-17 10:39:59 |
By :
{Cyberman} |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ตัวอย่างผลลัพธ์ ด้วยครับ คำถามไม่เคลียร์ แต่ละfield ยังไง ของทุกคน หรือเปล่า บอกให้ชัดเจนครับ
แต่วิธีการมันคล้ายๆ กันจากรูปแบบที่เป็นตัวอย่างนั้นแหล่ะครับ
sum( if(condition, 1, 0)) as x
if( field is null , กำหนดค่าเมื่อ condition เป็นจริง, กำหนดค่าเมื่อ condition เป็นเท็จ)
if( field > '' , กำหนดค่าเมื่อ condition เป็นจริง, กำหนดค่าเมื่อ condition เป็นเท็จ) สำหรับ type varchar
if( field > 0 , กำหนดค่าเมื่อ condition เป็นจริง, กำหนดค่าเมื่อ condition เป็นเท็จ) สำหรับ type number
Code (SQL)
select user_id
, sum( if(fld_1 is null, 1,0) as count_fld_1
, sum( if(fld_2 is null, 1,0) as count_fld_s
from table_name
group by user_id
|
ประวัติการแก้ไข 2021-01-17 21:28:56
 |
 |
 |
 |
Date :
2021-01-17 21:28:02 |
By :
Chaidhanan |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|