Tengo dos bases de datos, una de mis contactos y otra de sus pedidos vinculados por su contact_id. Me gustaría crear una nueva columna orders.exclude_from_statistics
en esta última cuando el donante es Great Benefactor
o que el campo caimpaing
es nuit
.
CREATE TABLE IF NOT EXISTS `contacts` (
`Contact ID` int(6) unsigned NOT NULL,
`Great Benefactor` tinyint(1) NOT NULL,
PRIMARY KEY (`contact_id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`id`, `user_id`, `Great Benefactor`) VALUES
('1', '1'),
('2', '0'),
('3', '0'),
('4', '0');
CREATE TABLE IF NOT EXISTS `orders` (
`Order ID` int(6) unsigned NOT NULL,
`Amount` int(6) unsigned NOT NULL,
`Contact ID` int(6) unsigned NOT NULL,
`Campaign` VARCHAR(255)
PRIMARY KEY (`contact_id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `orders` (`id`, `Amount`, `contact_id`) VALUES
('1', '100',1, NULL),
('2', '20', 2, NULL),
('3', '10', 3, `nuit`),
('4', '30', 1, NULL);
Pensé hacer:
SELECT * FROM orders LEFT JOIN contacts.`Great Benefactor` ON concats.`Contact ID` = orders.`Contact ID`;
Pero no crea una nueva tabla. Probablemente necesite un ALTER TABLE:
UPDATE orders
INNER JOIN contacts ON orders.id = contacts.`Contact ID`
IF contacts.`Great Benefactor` = true OR orders.Campaign = `nuit`
SET orders.exclude_from_statistics = 1
ELSE
SET orders.exclude_from_statistics = 0
;
No soy seguro de ALTER TABLE pensaba tambien en UPDATE.
El contexto es hacer esto cada noche en mi ETL:
crm_orders_exclude_from_statistics.py
from etl.utils.logging import info
from etl.mysql.connect import db
def add_column_exclude_from_statistics():
with db as c:
# Create new columns where exclude_from_statistics
info("Creating column exclude from statistics")
c.execute("""
UPDATE orders
INNER JOIN contacts ON orders.id = contacts.`Contact ID`
IF contacts.`Great Benefactor` = true OR orders.Campaign = `nuit`
SET orders.exclude_from_statistics = 1
ELSE
SET orders.exclude_from_statistics = 0
;
""")
def main():
info("Table crm.orders")
add_column_exclude_from_statistics()
if __name__ == '__main__':
main()
Que ejecuto cada noche desde main.py
import ...
def main():
crm_orders_exclude_from_statistics.main()
info('End ETL main process')
if __name__ == '__main__':
main()