Guest User

Untitled

a guest
Sep 24th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. #Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.
  2.  
  3. #For example:
  4. #| id | name | sex | salary |
  5. #|----|------|-----|--------|
  6. #| 1 | A | m | 2500 |
  7. #| 2 | B | f | 1500 |
  8. #| 3 | C | m | 5500 |
  9. #| 4 | D | f | 500 |
  10. #After running your query, the above salary table should have the following rows:
  11. #| id | name | sex | salary |
  12. #|----|------|-----|--------|
  13. #| 1 | A | f | 2500 |
  14. #| 2 | B | m | 1500 |
  15. #| 3 | C | f | 5500 |
  16. #| 4 | D | m | 500 |
  17.  
  18. #1.
  19. #UPDATE table_name SET col_name = new_value WHERE col_name = value_x;
  20.  
  21. #2.
  22. create database test_one;
  23. use test_one;
  24.  
  25. CREATE TABLE recipes (
  26. recipe_id INT NOT NULL,
  27. recipe_name VARCHAR(30) NOT NULL,
  28. PRIMARY KEY (recipe_id),
  29. UNIQUE (recipe_name)
  30. );
  31.  
  32. INSERT INTO recipes
  33. (recipe_id, recipe_name)
  34. VALUES
  35. (1,"Tacos"),
  36. (2,"Tomato Soup"),
  37. (3,"Grilled Cheese");
  38.  
  39. select * from recipes;
  40.  
  41. show tables;
  42.  
  43. #select * from salary;
  44. #select id, count(*) from salary GROUP BY id;
  45. #select distinct * from salary;
  46.  
  47. #drop table salary;
  48.  
  49. CREATE TABLE salary (
  50. id INT NOT NULL,
  51. name VARCHAR(30) NOT NULL,
  52. sex varchar(30),
  53. salary int,
  54. PRIMARY KEY (id),
  55. UNIQUE (name)
  56. );
  57.  
  58. select * from salary;
  59. INSERT INTO salary
  60. (id,name,sex,salary)
  61. VALUES
  62. (1,'A','f',2500),
  63. (2,'B','m',1500),
  64. (3,'C','m',300),
  65. (4,'D','m',500);
  66.  
  67. UPDATE salary
  68. SET sex = CASE WHEN sex = 'm' THEN 'f'
  69. WHEN sex = 'f' THEN 'm' END
  70. WHERE id IN (1,2,3,4); #???where
  71.  
  72. #3.
  73. #CASE expression
  74. # WHEN condition1 THEN result1
  75. # WHEN condition2 THEN result2
  76. # ...
  77. # WHEN conditionN THEN resultN
  78. # ELSE result
  79. #END
  80.  
  81. #4.
  82. #SELECT column_name(s)
  83. #FROM table_name
  84. #WHERE column_name IN (value1,value2,...)
Add Comment
Please, Sign In to add comment