mysql: 3 tips
Blogs20102010-12-15
(1) Left Join Left Join is used for multi-tables select. To select columns from different tables, which maybe null, duplicate, relative each other, use Left Join for the case.
The following sql selects a certain record which includes columns in 3 tables:
SELECT * FROM users u left join (questions q, answers a) on ( a.uid = u.uid AND q.qid = a.qid1) where u.sin = ββ . $sin. ββ and birthdate = ββ. $dob . βββ;
Here is a more complex example:
SELECT names.codename, s1.score AS βScore1β, s1.comment AS βComments1β, s2.score AS βScore2β, s2.comment AS βComments2β, SUM(st.score) AS βTotalβ FROM students names LEFT JOIN scores s1 ON s1.act_id=1 AND names.id=s1.student_id LEFT JOIN scores s2 ON s2.act_id=2 AND names.id=s2.student_id LEFT JOIN scores st ON names.id=st.student_id WHERE names.codename β GROUP BY names.codename ORDER BY names.codename;
(2)INSERT β¦ ON DUPLICATE KEY UPDATE
Suppose we have a user_detail table, some user fill up it, some not. The flow like this: . if the record exists, update it, . if not, insert the record.
What is the samplest way to process user_detail table when user insert/update ? MySQL has the answer. Donβt need stored procedure, or function, just the extend βINSERTβ syntax. INSERT β¦ ON DUPLICATE KEY UPDATE If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect:
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
and:
UPDATE table SET c=c+1 WHERE a=1;
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated.
So, for a certain user_detail record, the following will excute($uid is primary key and unique):
- insert if $uid not exists, or- update if $uid exists
INSERT INTO user_details values(β.$uid.β,β.$qid1.β,ββ.$answer1.ββ,β.$qid2.β,ββ.$answer2.ββ,Now()) on duplicate key update qid1=β.$qid1.β,answer1=ββ.$answer1.ββ,qid2=β.$qid2.β,answer2=ββ.$answer2.ββ,putdate=Now()
very cool.
(3) import databse/table Except phpMyAdmin, I found the easiest way to import database/table is:
$ mysql -u test -p -D test -h localhost <users.sql
Not mysqldump, or restore etc.
