I had a lot of help in writing all of this in php (mainly the first long query).
// Query the database for data
$query = "SELECT cards.card_id, concat(title, \" By Amy\") AS TitleConcat,
description, meta_description,
seo_keywords,concat(\"http://www.amyadele.com/attachments//cards/\",cards.card_id,\"/\",card_image) AS ImageConcat,price
FROM cards, card_cheapest
WHERE cards.card_id = card_cheapest.card_id
ORDER BY card_id";
$result = mysql_query($query);
// Open file for writing
$myFile = "googleproducts.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
// Loop through returned data and write (append) directly to file
fprintf($fh, "%-25s %-200s %-800s %-200s %-800s %-800s\n", "id", "label","description","price","image","seo keywords");
fprintf($fh, "\n");
while ($row = mysql_fetch_assoc($result)) {
fprintf($fh, "%-25s %-200s %-800s %-200s %-800s %-800s\n", $row['card_id'], $row['TitleConcat'], $row['description'],$row['price'],$row['ImageConcat'], $row['seo_keywords']);
}
// Close out the file
fclose($fh);
echo "The file has been written sucessfully to googleproducts.txt. It will run again tomorrow at 12:00pm."
?>
However, over the last couple of days I have written a couple other queries which leads me to my question. Would it be easier to somehow stick this other queries into the first "select", or would it be easier to set up multiple queries and then just insert that into the rows as well (I dont even know if that is even possible).
Query: Selecting the Min Price
select card_id, min(card_price) from card_lookup_values where card_price > 0 group by card_id;
Query: Creating URL Structure
SELECT CONCAT('http://amyadele.com/', cards.title, '/', categories.seoname, '/', cards.seoname),cards.card_id
FROM cards
LEFT JOIN card_categories
ON card_categories.card_id = cards.card_id
LEFT JOIN categories
ON card_categories.category_id = categories.category_id ORDER by card_id;
I guess my question is is it best to set up my queries (which I already know work) into multiple variables and then somehow push that into the table format I have set up, or to somehow format all of these queries into one long query?
I recently just wrote
SELECT
replace(lower(concat( 'http://www.amyadele.com/', pcat.seoname,'/',cat.seoname, '/', cards.seoname, '.htm' )),' ','+') AS link,
concat(pcat.name,'>',cat.name) as category,
replace(lower(concat( 'http://www.amyadele.com/', cat.seoname, '/', cards.seoname, '.htm' )),' ','+') AS add_to_cart_link
FROM cards
INNER JOIN card_categories cc ON cards.card_id = cc.card_id AND cards.card_live = 'y' AND cards.active = 'y' AND cc.active = 'Y'
INNER JOIN categories cat ON cat.category_id = cc.category_id AND cat.active = 'Y'
INNER JOIN categories pcat ON cat.parent_category_id = pcat.category_id
INNER JOIN card_lookup_values clv on clv.card_id=cards.card_id and clv.lookup_detail_id
WHERE cat.parent_category_id <>0
ORDER BY cc.card_id
However, I am really confused on how to even add this now
You can use 'joins' to aggregate all of this information into a single response from the DB. I don't know your exact schema, so some of this is just a guess, but here is how I would start.
SELECT
cards.card_id,
concat(cards.title, ' By Amy') AS TitleConcat,
cards.description,
cards.meta_description,
cards.seo_keywords,
concat('http://www.amyadele.com/attachments//cards/',cards.card_id,'/',cards.card_image) AS ImageConcat,
card_cheapest.price,
card_import.author,
min(card_lookup_values.card_price)
FROM
cards
join card_cheapest on cards.card_id = card_cheapest.card_id
left join card_import on card_import.card_id = cards.card_id
join card_lookup_values on card_lookup_values.card_id = cards.card_id
WHERE card_lookup_values.card_price > 0
GROUP BY
cards.card_id
ORDER BY
cards.card_id
Related
I have a fairly complex query (to me) that returns duplicate results ONLY when the parameter passed results in 'dest_xdock: ' . $row['dest_xdock'] as a certain value. Can anyone identify why this is happening in the Query? I don't have duplicates of this in the table that I can see. Here is the query:
select
`orig_lookup`.`zipcode` AS `orig_zipcode`,
`orig_lookup`.`state` AS `orig_state`,
`orig_lookup`.`svcnotes` AS `orig_svcnotes`,
`orig_lookup`.`svcterms` AS `orig_svcterms`,
`orig_lookup`.`daysout` AS `orig_daysout`,
`orig_lookup`.`daysin` AS `orig_daysin`,
`orig_lookup`.`pcity` AS `orig_city`,
`orig_lookup`.`scac` AS `orig_scac`,
`orig_lookup`.`xdock` AS `orig_xdock`,
`orig_lookup`.`scac2` AS `orig_scac2`,
`orig_lookup`.`xdock2` AS `orig_xdock2`,
`orig_lookup`.`scac3` AS `orig_scac3`,
`orig_lookup`.`xdock3` AS `orig_xdock3`,
`orig_ssas`.`ssa` AS `orig_ssa`,
`orig_hcas`.`hca` AS `orig_hca`,
`dest_lookup`.`zipcode` AS `dest_zipcode`,
`dest_lookup`.`state` AS `dest_state`,
`dest_lookup`.`svcnotes` AS `dest_svcnotes`,
`dest_lookup`.`svcterms` AS `dest_svcterms`,
`dest_lookup`.`daysout` AS `dest_daysout`,
`dest_lookup`.`daysin` AS `dest_daysin`,
`dest_lookup`.`pcity` AS `dest_city`,
`dest_lookup`.`scac` AS `dest_scac`,
`dest_lookup`.`xdock` AS `dest_xdock`,
`dest_lookup`.`scac2` AS `dest_scac2`,
`dest_lookup`.`xdock2` AS `dest_xdock2`,
`dest_lookup`.`scac3` AS `dest_scac3`,
`dest_lookup`.`xdock3` AS `dest_xdock3`,
`dest_ssas`.`ssa` AS `dest_ssa`,
`dest_hcas`.`hca` AS `dest_hca`,
`tbl_matx_20160321`.`trmnljoin` AS `TrmnlMatx`,
`tbl_matx_20160321`.`trmnlsvcdays` AS `TrmnlSvcDays`,
`tbl_matx_20160321`.`trmnltranspts` AS `TrmnlTransPts`,
IF(ISNULL(`orig_lookup`.`daysin`+ `dest_lookup`.`daysout`+ `tbl_matx_20160321`.`trmnlsvcdays`), 'No Service',(`orig_lookup`.`daysin`+ `dest_lookup`.`daysout`+ `tbl_matx_20160321`.`trmnlsvcdays`)) AS `TotalSvcDays`
FROM ((`tbl_uscomp_20160321` AS `orig_lookup` LEFT JOIN `tbl_hcas_20160321` AS `orig_hcas` ON `orig_lookup`.`zipcode` = `orig_hcas`.`zipcode` LEFT JOIN `tbl_ssas_20160321` AS `orig_ssas` ON `orig_lookup`.`zipcode` = `orig_ssas`.`zipcode`)
INNER JOIN (`tbl_uscomp_20160321` AS `dest_lookup` LEFT JOIN `tbl_hcas_20160321` AS `dest_hcas` ON `dest_lookup`.`zipcode` = `dest_hcas`.`zipcode` LEFT JOIN `tbl_ssas_20160321` AS `dest_ssas` ON `dest_lookup`.`zipcode` = `dest_ssas`.`zipcode`)
INNER JOIN `tbl_matx_20160321` ON (`orig_lookup`.`xdock` = `tbl_matx_20160321`.`otrmnl` AND `dest_lookup`.`xdock` = `tbl_matx_20160321`.`dtrmnl`))
WHERE `orig_lookup`.`zipcode` = '$ziporig' AND `dest_lookup`.`zipcode` = '$zipdest'",
I have a dhtmlx-grid created from multiple tables. And I am able to edit the main table but not the joined ones.
The dhtmlx guides are rather vague on creating a grid from multiple tables and making it fully editable.
I followed the steps here:
http://docs.dhtmlx.com/connector__php__complex_queries.html#complexqueries
http://docs.dhtmlx.com/connector__php__basis.html#loadingfromdatabase
and tried to create a connection, but failed.
I'm using their php-connector and the code that I tried is as follows:
$jpnx_regs = new GridConnector($conn,'MySQL'); // connector initialization
$jpnx_regs->sql->attach("Update","
UPDATE wp_japanextion_attendance_data
LEFT JOIN wp_buyer_employee
ON wp_buyer_employee.ID = wp_japanextion_attendance_data.ID_employee
LEFT JOIN wp_buyer_company
ON wp_buyer_company.ID = wp_buyer_employee.ID_company
SET
reg_user='{reg_user}',
reservation_date='{reservation_date}',
reservation_hour='{reservation_hour}',
copy_company_name='{copy_company_name}',
copy_company_TEL='{copy_company_TEL}',
copy_name='{copy_name}',
copy_mobile_TEL='{copy_mobile_TEL}',
copy_email='{copy_email}',
rec_creation_date='{rec_creation_date}',
iploc='{iploc}',
trackvia_inserted='{trackvia_inserted}'
WHERE id='{id}'
");
$jpnx_regs->render_complex_sql("
SELECT
*, wp_japanextion_attendance_data.ID AS jpnx_ID,
wp_buyer_employee.ID AS employee_ID,
wp_buyer_company.ID AS buyer_ID,
FROM
wp_japanextion_attendance_data
LEFT JOIN wp_buyer_employee
ON wp_buyer_employee.ID = wp_japanextion_attendance_data.ID_employee
LEFT JOIN wp_buyer_company
ON wp_buyer_company.ID = wp_buyer_employee.ID_company
WHERE
reservation_date LIKE '%November%' OR
reservation_date LIKE '%December%' OR
reservation_date LIKE '%January%'
", "jpnx_ID","
reg_user,reservation_date,reservation_hour,company_name,company_TEL,name,mobile_TEL,email,rec_creation_date,iploc,trackvia_inserted,ID
");
↑ Just as their guide says. I first initialize the grid like this:
$jpnx_regs = new GridConnector($conn,'MySQL');
Then I attach the update action:
$jpnx_regs->sql->attach("Update"," ... sql code here
Then I render the grid with the render_complex_sql.
$jpnx_regs->render_complex_sql("
BTW, just in case, here down below is my working code for my grid from multiple tables but I can only update the main table:
$jpnx_regs = new GridConnector($conn,'MySQL');
if ($jpnx_regs->is_select_mode())
$jpnx_regs->render_sql("
SELECT
*, wp_japanextion_attendance_data.ID AS jpnx_ID,
wp_buyer_employee.ID AS employee_ID,
wp_buyer_company.ID AS buyer_ID,
FROM
wp_japanextion_attendance_data
LEFT JOIN wp_buyer_employee
ON wp_buyer_employee.ID = wp_japanextion_attendance_data.ID_employee
LEFT JOIN wp_buyer_company
ON wp_buyer_company.ID = wp_buyer_employee.ID_company
", "jpnx_ID","reg_user,reservation_date,reservation_hour,company_name,company_TEL,name,mobile_TEL,email,rec_creation_date,iploc,trackvia_inserted,ID
");
else //code for other operations - i.e. update/insert/delete
$jpnx_regs->render_table("wp_japanextion_attendance_data","id","
reg_user,reservation_date,reservation_hour,copy_company_name,copy_company_TEL,copy_name,copy_mobile_TEL,copy_email,rec_creation_date,iploc,trackvia_inserted");
I am trying to use an if statement to increase a db row ($row[cost]) 20% up to but not including a different row. As of now my code is: $row-->cost/.80 so I basically want it to not hit the maximumbid which is held in this query:
$result = $wpdb->get_results( "SELECT bp.*, b.company
FROM `windows_brands_products` bp
LEFT JOIN `windows_brands` b
ON bp.brand_id = b.id
JOIN Windows_last_submissions ls
JOIN windows_materials wm
WHERE ls.username = '$current_user->user_login'
AND bp.width = ROUND(ls.width)
AND bp.height = ROUND(ls.height)
AND bp.material IN (wm.name)
AND bp.type = ls.type
AND IF (ls.minimumbid != '0.00',bp.cost BETWEEN ls.minimumbid
AND ls.maximumbid,bp.cost <= ls.maximumbid)
ORDER BY b.company ASC");
Question being how do I reference row minimumbid so I can prevent this 80%increase from hitting maximumbid?
i am having trouble creating a single mysql query for what i am trying to do here.
first off, i will show you the table structures and fields of the tables i am using for this particular query:
users:
- id
- name
- photo_name
- photo_ext
user_attacks:
- id
- level
user_news_feed:
- id
- id_user
- id_status
- id_attack
- id_profile
- id_wall
- the_date
user_status:
- id
- status
user_wall:
- id
- id_user
- id_poster
- post
whenever the user posts an attack, or status update, updates their profile, or posts on someones wall, it inserts the relevant data into its respective table and also inserts a new row into the user_news_feed table.
now, what i want to do is select the last 10 news feed items from the database. these news feed items need to grab relevant data from other tables as long as their value is not 0. so if the news feed is for a status update, the id_status would be the id of the status update in the user_status table, and the "status" would be the data needing to be selected via a left join. hope that makes sense.
heres my first mysql query:
$sql = mysql_query("select n.id_user, n.id_status, n.id_attack, n.id_profile, n.id_wall, n.the_date, u.id, u.name, u.photo_name, u.photo_ext, s.status
from `user_news_feed` as n
left join `users` u on (u.id = n.id_user)
left join `user_status` s on (s.id = n.id_status)
where n.id_user='".$_GET['id']."'
order by n.id desc
limit 10
");
now this works great, except for 1 problem. as you can see the user_wall table contains the id's for 2 different users. id_user is the user id the post is being made for, and id_poster is the user id of the person making that wall post. if the user makes a wall post on his/her own wall, it is inserted into the database as a status update into the user_status table instead.
so i have a conditional statement within the while loop for the first query, which has another sql query within it. here is the whole code for the while loop and second sql query:
while ($row = mysql_fetch_assoc($sql))
{
if ($row['id_wall'] != 0)
{
$sql_u = mysql_query("select u.id, u.name, u.photo_name, u.photo_ext, w.post
from `user_wall` as w
left join `users` u on (u.id = w.id_poster)
where w.id='".$row['id_wall']."'
");
while ($row_u = mysql_fetch_assoc($sql_u))
{
$row['photo_name'] = $row_u['photo_name'];
$row['photo_ext'] = $row_u['photo_ext'];
$row['id_user'] = $row_u['id'];
$row['name'] = $row_u['name'];
$content = $row_u['post'];
}
}
else
{
if ($row['id_status'] != 0)
$content = $row['status'];
else if ($row['id_attack'] != 0)
$content = '<i>Had an attack</i>';
else if ($row['id_profile'] != 0)
$content = '<i>Updated profile</i>';
}
echo '<li'.(($count == $total_count) ? ' class="last"' : '').'>';
echo '<img src="images/profile/'.$row['photo_name'].'_thumb.'.$row['photo_ext'].'" alt="" />';
echo '<div class="content">';
echo '<b>'.$row['name'].'</b>';
echo '<span>'.$content.'</span>';
echo '<small>'.date('F j, Y \a\t g:ia', $row['the_date']).'</small>';
echo '</div>';
echo '<div style="clear: both;"></div>';
echo '</li>';
}
i hope what i am trying to do here makes sense. so basically i want to have both sql queries ($sql, and $sql_u) combined into a single query so i do not have to query the database every single time when the user_news_feed item is a wall post.
any help would be greatly appreciated and i apologise if this is confusing.
SELECT n.id_user, n.id_status, n.id_attack, n.id_profile, n.id_wall, n.the_date,
u.id, u.name, u.photo_name, u.photo_ext, s.status,
w.id AS wall_user_id, w.name AS wall_user_name,
w.photo_name AS wall_user_photo_name,
w.photo_ext AS wall_user_photo_ext,
w.post
FROM user_news_feed AS n
LEFT JOIN users AS u ON (u.id = n.id_user)
LEFT JOIN user_status s ON (s.id = n.id_status)
LEFT JOIN (SELECT a.id AS id_wall, b.id, b.name, b.photo_name, b.photo_ext, a.post
FROM user_wall AS a
LEFT JOIN users AS b ON (b.id = a.id_poster)
) AS w ON w.id_wall = n.id_wall
WHERE n.id_user = ?
ORDER BY n.id desc
LIMIT 10
The '?' is a placeholder where you can provide the value of $_GET['id'].
Basically, this adds an extra outer join, to the main query (and some extra columns, which will be NULL if the news feed event is not a wall posting), but the outer join is itself the result of an outer join.
Back again ;)
Anyway, forget about merging the queries in my opinion.
What you should do instead is to do the first query, loop through all the results and store all "id_wall"s in a separate array... then rather than doing a separate query per "id_wall" you do this:
$wallids = array();
while ($row = mysql_fetch_assoc($sql))
{
$wallids[] = $row['id_wall'];
// also store the row wherever you want
}
$sql_u = mysql_query("select u.id, u.name, u.photo_name, u.photo_ext, w.post
from `user_wall` as w
left join `users` u on (u.id = w.id_poster)
where w.id IN ('".implode(',', $wallids) ."')
");
$wallids being an array with all the "id_wall"s. So now you have a total of 2 queries.
I have two tables(entries and tags) with a many-to-many linking table. Right now, I'm making a query to retrieve all the entries that meet my criteria, and a query for each entry to retrieve the tags.
Would there be a way to say, have the tags returned through a new column as an array in the first query?
This query:
SELECT e.id entry_id
, GROUP_CONCAT(t.txt ORDER BY t.txt) tags
FROM entry e
LEFT JOIN entry_tag et
ON e.id = et.entry_id
LEFT JOIN tag t
ON et.tag_id = t.id
GROUP BY e.id
Will return the tags as a comma-separated list. You can read up on GROUP_CONCAT for more options: http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_group-concat
In your app you should be able to expand this into an array quite easily. For example in php, you could use explode: http://php.net/manual/en/function.explode.php
If you need more attributes from the tag or entry_tag tables, you can either add yet more GROUP_CONCAT columns, or think of some serialization format for your data (like JSON) and use GROUP_CONCAT on that, or you can simply return multiple rows per entry and process the results in the application to keep tags together with entries:
$sql = '
SELECT e.id entry_id
, t.id tag_id
, t.txt tag_text
, t.published tag_published
FROM entry e
LEFT JOIN entry_tag et
ON e.id = et.entry_id
LEFT JOIN tag t
ON et.tag_id = t.id
ORDER BY e.id
';
$result = mysql_query($ql);
$entry_id = NULL;
$entry_rows = NULL;
while ($row = mysql_fetch_assoc($result)) {
if ($entry_id != $row['entry_id']) {
if (isset($entry_id)) { //ok, found new entry
process_entry($entry_rows); //process the rows collected so far
}
$entry_id = $row['entry_id'];
$entry_rows = array();
}
$entry_rows[] = $row; //store row for his entry for later processing
}
if (isset($entry_id)){ //process the batch of rows for the last entry
process_entry($entry_rows);
}
You can use GROUP BY and GROUP_CONCAT function to get all tags at once as a concatenated string. http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html