Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Bagaimana cara membandingkan 2 daftar dan menggabungkannya dengan Python/MySQL?

Oke, mari bersenang-senang...

mysql> create table so (a int, b char, c char, d char, e char, f char, `key` int, dupe char);
Query OK, 0 rows affected (0.05 sec)

mysql> insert into so values (1, 'd', 'c', 'f', 'k', 'l', 1, 'x'), (2, 'g', null, 'h', null, 'j', 1, null), (3, 'i', null, 'h', 'u', 'u', 2, null), (4, 'u', 'r', null, null, 't', 2, 'x');
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from so order by a;
+------+------+------+------+------+------+------+------+
| a    | b    | c    | d    | e    | f    | key  | dupe |
+------+------+------+------+------+------+------+------+
|    1 | d    | c    | f    | k    | l    |    1 | x    |
|    2 | g    | NULL | h    | NULL | j    |    1 | NULL |
|    3 | i    | NULL | h    | u    | u    |    2 | NULL |
|    4 | u    | r    | NULL | NULL | t    |    2 | x    |
+------+------+------+------+------+------+------+------+
4 rows in set (0.00 sec)
Python 2.6.5 (r265:79063, Mar 26 2010, 22:43:05) 
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> db = MySQLdb.connect(host="127.0.0.1", db="test")
>>> c = db.cursor()
>>> c.execute("SELECT a, b, c, d, e, f, `key`, dupe FROM so")
4L
>>> rows = c.fetchall()
>>> rows
((1L, 'd', 'c', 'f', 'k', 'l', 1L, 'x'), (4L, 'u', 'r', None, None, 't', 2L, 'x'), (2L, 'g', None, 'h', None, 'j', 1L, None), (3L, 'i', None, 'h', 'u', 'u', 2L, None))
>>> data = dict()
>>> for row in rows:
...  key, isDupe = row[-2], row[-1]
...  if key not in data:
...   data[key] = list(row[:-1])
...  else:
...   for i in range(len(row)-1):
...    if data[key][i] is None or (not isDupe and row[i] is not None):
...     data[key][i] = row[i]
... 
>>> data
{1L: [2L, 'g', 'c', 'h', 'k', 'j', 1L], 2L: [3L, 'i', 'r', 'h', 'u', 'u', 2L]}



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Alat debugging MySQL memperlambat kueri?

  2. mySQL:Menggunakan jarak Levenshtein untuk menemukan duplikat dalam 20.000 baris

  3. ubah format tanggal default laravel sql query

  4. Apa perbedaan antara tipe data BLOB dan TEXT di MySQL?

  5. Python Matplotlib dan MySQL dan Ginput